package com.luoqiu.yygh.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.luoqiu.yygh.common.exception.YyghException;
import com.luoqiu.yygh.common.helper.JwtHelper;
import com.luoqiu.yygh.common.result.ResultCodeEnum;
import com.luoqiu.yygh.model.user.UserInfo;
import com.luoqiu.yygh.user.mapper.UserInfoMapper;
import com.luoqiu.yygh.user.service.UserInfoService;
import com.luoqiu.yygh.vo.user.LoginVo;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Override
    public Object loginPhone(LoginVo loginVo) {
        Map<String, Object> m = new HashMap<>();

        String phone = loginVo.getPhone();
        String code = loginVo.getCode();
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)) {
            throw new YyghException(ResultCodeEnum.PARAM_ERROR);
        }

        // 验证验证码是否正确

        // 判断是否是第一次登录 是 就注册
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("phone", phone);
        UserInfo userInfo = baseMapper.selectOne(wrapper);
        if (userInfo == null) {
            userInfo = new UserInfo();
            userInfo.setStatus(1);
            userInfo.setName("");
            userInfo.setPhone(phone);
            baseMapper.insert(userInfo);
        }
        m.put("user", userInfo);
        String token = JwtHelper.createToken(userInfo.getId(), userInfo.getName());
        m.put("token", token);
        return m;
    }
}
